﻿Imports System
Imports System.Windows.Forms
Imports DevExpress.XtraReports.UserDesigner
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient

Public Class SaveCommandHandler
    Implements ICommandHandler
    Private panel As XRDesignPanel

    Public Sub New(ByVal panel As XRDesignPanel)
        Me.panel = panel
    End Sub

    Public Overridable Sub HandleCommand(ByVal command As ReportCommand, _
    ByVal args() As Object, ByRef handled As Boolean) Implements ICommandHandler.HandleCommand
        If (Not CanHandleCommand(command)) Then
            Return
        End If

        ' Save a report.
        Save()

        ' Set handled to true to avoid the standard saving procedure to be called.
        handled = True
    End Sub

    Public Overridable Function CanHandleCommand(ByVal command As ReportCommand) _
    As Boolean Implements ICommandHandler.CanHandleCommand
        ' This handler is used for SaveFile, SaveFileAs and Closing commands.
        Return command = ReportCommand.SaveFile OrElse command = _
        ReportCommand.SaveFileAs
    End Function

    Private Sub Save()
        ' Write your custom saving here.
        Dim str As String
        str = "UPDATE Reports SET ReportFile = @ReportFile WHERE ID = " & intReportID
        Dim cmd As New SqlCommand(str, gCnnPCE)
        'Designer.SaveReport("C:\TempReport.repx")
        panel.Report.SaveLayout("C:\TempReport.repx")
        Dim br As New IO.BinaryReader(New IO.FileStream("C:\TempReport.repx", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read))
        Dim arr() As Byte = br.ReadBytes(br.BaseStream.Length)
        cmd.Parameters.Add("ReportFile", SqlDbType.Image).Value = arr
        If cmd.ExecuteNonQuery > 0 Then
            MsgBox("Report Saved.")
            br.Close()
            DeleteTempReport()
        End If

        ' For instance:
        ' panel.Report.SaveLayout("c:\report1.repx")

        ' Prevent the "Report has been changed" dialog from being shown.
        panel.ReportState = ReportState.Saved
    End Sub

    Private Sub DeleteTempReport()
        Try
            If File.Exists("C:\TempReport.repx") = True Then
                File.Delete("C:\TempReport.repx")
            End If
        Catch ex As Exception

        End Try
    End Sub
End Class
